package com.gitee.sop.message.sms;

import com.gitee.sop.message.Sender;
import com.gitee.sop.message.manager.SenderManagerServiceImpl;
import com.gitee.sop.message.util.AESUtil;
import com.gitee.sop.message.util.HttpUtil;
import com.gitee.sop.message.util.MapUtil;
import com.gitee.sop.message.util.ObjectUtil;
import com.gitee.sop.message.util.scheduler.SchedulerUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;


public class YiMeiSmsSender implements Sender {
    @Override
    public boolean send(String type,String phone, String message, Map<String, Object> smsSenderParameter) throws Exception {
        String title = smsSenderParameter.get("ycompany").toString();
        if (SenderManagerServiceImpl.SenderEnum.sms.getType().equals(type)) {
            title = StringUtils.isNotBlank(title) ? "【" + title + "】" : "【蓝星云开放平台】";
        } else if (SenderManagerServiceImpl.SenderEnum.email.getType().equals(type)) {
            title = StringUtils.isNotBlank(title) ? title : "蓝星云开放平台";
        }
        Map<String, Object> parameterMap = new HashMap<>(2);
        parameterMap.put("mobile", phone);
        parameterMap.put("content", title + message);
        String paramJson = ObjectUtil.toJson(parameterMap);
        byte[] data = paramJson.getBytes(Charset.forName("UTF-8"));
        byte[] outData = AESUtil.getInstance().encrypt(data, smsSenderParameter.get("ysecretKey").toString().getBytes());
        HttpUtil.HttpResponse response = null;
        try {
            response = HttpUtil.connection(smsSenderParameter.get("ysmsApi").toString())
                    .setHeader("appId", smsSenderParameter.get("yappId").toString()).setPostParameter(outData).post();
        } catch (IOException e) {
            throw e;
        }
        byte[] inData = AESUtil.getInstance().decrypt(response.getResponse(), smsSenderParameter.get("ysecretKey").toString().getBytes());
        return true;
    }

    @Override
    public boolean syncSend(String phone, String message, String title, Map<String, Object> smsSenderParameter) throws Exception {
        SchedulerUtil.schedule(() -> {
            send(phone, message, title, smsSenderParameter);
        });
        return true;
    }

    @Override
    public Map<String, Object> senderParameterTemplate() {
        return MapUtil.builder().elem("yappId", "由亿美后台获取，类似：KUCD-EBY-EMS1-1YGGG")
                .elem("ysecretKey", "由亿美后台获取，类似：EC6563202771328D")
                .elem("yhost", "由亿美提供，类似：http://bjmtn.b2m.cn")
                .elem("ysmsApi", "由亿美提供，类似：http://bjmtn.b2m.cn/inter/sendSingleSMS").build();
    }
}
